package com.dailyblue.java.project.estate.gateway.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dailyblue.java.project.estate.gateway.mapper.EstateManagerMapper;
import com.dailyblue.java.project.estate.gateway.service.EstateManagerService;
import com.dailyblue.project.estate.commons.bean.EstateManager;
import com.dailyblue.project.estate.commons.util.JsonResult;
import com.dailyblue.project.estate.commons.util.JwtConfig;
import com.dailyblue.project.estate.commons.util.ResultCode;
import com.dailyblue.project.estate.commons.util.ResultTool;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class EstateManagerServiceImpl extends ServiceImpl<EstateManagerMapper, EstateManager> implements EstateManagerService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public JsonResult login(String username, String password) {
        QueryWrapper<EstateManager> wrapper = new QueryWrapper<>();
        wrapper.eq("login_name", username);
        wrapper.eq("password", password);
        EstateManager manager = getBaseMapper().selectOne(wrapper);
        if (manager == null) {
            return ResultTool.fail(ResultCode.USER_CREDENTIALS_ERROR);
        }
        // 生成token
        String token = JwtConfig.getJwtToken(manager);
        // 保存到redis
        ValueOperations<String, String> values = stringRedisTemplate.opsForValue();
        values.set("token:" + manager.getId(), token, 1, TimeUnit.DAYS);
        return ResultTool.success(token);
    }
}
